package com.loe.logger.util

import android.content.Context
import android.content.res.Resources
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.WindowManager
import com.loe.logger.LoeLogger

class LoeTopTouch(private val context: Context)
{
    private var isDown = false

    private var lastTouchTime = 0L

    fun dispatchTouchEvent(e: MotionEvent)
    {
        when (e.action)
        {
            MotionEvent.ACTION_DOWN ->
            {
                if (e.rawY < bottom && e.rawX > left && e.rawX < right)
                {
                    isDown = true
                }
            }
            MotionEvent.ACTION_UP ->
            {
                if (isDown && System.currentTimeMillis() - lastTouchTime > 800 && e.rawY < bottom && e.rawX > left && e.rawX < right)
                {
                    LoeLogger.toLogger(context)
                    lastTouchTime = System.currentTimeMillis()
                }
                isDown = false
            }
        }
    }

    private val left = screenWidth() * 0.4

    private val right = screenWidth() * 0.6

    private val bottom = statusHeight() + px(50)

    private fun px(dp: Int): Int
    {
        return (dp * Resources.getSystem().displayMetrics.density).toInt()
    }

    private fun screenWidth(): Int
    {
        var mDisplayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(mDisplayMetrics)
        return mDisplayMetrics.widthPixels
    }

    private fun statusHeight(): Int
    {
        val resourceId: Int = context.resources.getIdentifier("status_bar_height", "dimen", "android")
        return context.resources.getDimensionPixelSize(resourceId)
    }
}